package com.mlz.mlzmall.ui.activity.act.personal;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.google.gson.Gson;
import com.mlz.mlzmall.R;
import com.mlz.mlzmall.bean.UserBean;
import com.mlz.mlzmall.custom.circleimageview.CircleImageView;
import com.mlz.mlzmall.ui.activity.act.base.TopTitleView;
import com.mlz.mlzmall.ui.activity.act.main.MainActivity;
import com.mlz.mlzmall.ui.activity.act.main.MyApplication;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.LoginUtils;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.RequestUtils;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.VolleyBaseActivity;
import com.mlz.mlzmall.ui.activity.act.personal.userLogin.LoginActivity;
import com.mlz.mlzmall.ui.activity.act.personal.userLogin.PostLoginOauth;
import com.mlz.mlzmall.ui.activity.act.personal.userLogin.RegistActivity;
import com.mlz.mlzmall.ui.adapter.PersonalAdapter;
import com.mlz.mlzmall.ui.dialog.CallDialog;
import com.mlz.mlzmall.ui.dialog.PhotoDialog;
import com.mlz.mlzmall.ui.model.GetInfoResponse;
import com.mlz.mlzmall.ui.model.PersonalModel;
import com.mlz.mlzmall.ui.model.StringTools;
import com.mlz.mlzmall.ui.model.UserInfo;
import com.mlz.mlzmall.ui.utils.mlz.ConfigInfo;
import com.mlz.mlzmall.ui.utils.mlz.Constans;
import com.mlz.mlzmall.ui.utils.mlz.DataSharedPress;
import com.mlz.mlzmall.ui.utils.mlz.URL;
import com.mlz.mlzmall.ui.utils.util.ACache;
import com.mlz.mlzmall.ui.utils.util.CacheUtils;
import com.mlz.mlzmall.ui.utils.util.LogUtils;
import com.mlz.mlzmall.ui.utils.util.SharedUtils;
import com.mlz.mlzmall.ui.utils.vali.AbStrUtil;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.bean.Image;


/**
 * 功能描述：个人中心界面
 * Created by benny on 2016/5/7.
 * ProjectName：mlzMall.
 */
public class PersonalActivity extends VolleyBaseActivity implements View.OnClickListener {
    private static final String TGA = "PersonalActivity";
    private ListView personal;
    private List<PersonalModel> list = new ArrayList<>();
    private RelativeLayout call_phone;
    private PersonalAdapter adapter;

    private View includeView;//个人中心中间的登录、注册按钮
    //登陆前布局相关
    private LinearLayout llPersonalCenter;
    private TextView tvLogin;//登录
    private TextView tvRegist;//注册

    //登陆后的布局控件
    private RelativeLayout rlPersonalCenter;
    private CircleImageView civUserImg;//用户头像
    private TextView tvUserName;//用户名
    private ImageView ivGender;//用户性别
    private ImageView loginPullRight;//箭头

    private TopTitleView mycenterTopTitle;//设置标题

    private Bitmap bitmap;
    private String filename;
    private boolean isLogin;
    private UserBean userBean;
    Intent intent;


    // 获取个人信息(三方登录成功)
    PostLoginOauth GetPersonInfoSucess;
    private String phoneId;
    private File headPath = null;
    DataSharedPress sharedPress;
    ACache mCache;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personal_layout);

        initView();
        setViewContent();
        initData();
        setViewClickListener();
        intent = getIntent();
        mCache = ACache.get(getApplication());
        phoneId = mCache.getAsString("phoneid");

        sharedPress = DataSharedPress.getSharedPress(getApplication(), phoneId);
        headPath = new File(Environment.getExternalStorageDirectory() + "/MLZmall/userInfo/" + phoneId + ".jpg");
//        Log.i(TGA, "头像第三方：" + headPath);

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    // 微信登陆成功的个人信息
    private void getInfoForLoginWeiXin() {
        if ("FROM_AUTHOR_LOGIN_SUCCESS".equals(intent.getAction())) {
            ArrayList array = intent.getCharSequenceArrayListExtra("data");
            GetPersonInfoSucess = (PostLoginOauth) array.get(0);
        }
    }

    private void initView() {
        mycenterTopTitle = (TopTitleView) findViewById(R.id.mycenter_top_title);
        personal = (ListView) findViewById(R.id.personal_list);

        //登陆前布局相关
        llPersonalCenter = (LinearLayout) findViewById(R.id.ll_personal_center);
        includeView = findViewById(R.id.include_center);
        tvLogin = (TextView) includeView.findViewById(R.id.tv_login);
        tvRegist = (TextView) includeView.findViewById(R.id.tv_regist);

        //登陆后的布局控件
        rlPersonalCenter = (RelativeLayout) findViewById(R.id.rl_personal_center);
        civUserImg = (CircleImageView) includeView.findViewById(R.id.user_img);
        tvUserName = (TextView) includeView.findViewById(R.id.user_name);
        ivGender = (ImageView) includeView.findViewById(R.id.img_gender);
        loginPullRight = (ImageView) includeView.findViewById(R.id.login_pull_right);
        //客服
        View call_v = LayoutInflater.from(this).inflate(R.layout.personal_item_layout_call, null);
        call_v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CallDialog.call(PersonalActivity.this, "4008628896");
            }
        });
        personal.addFooterView(call_v);

    }

    /**
     * 设置标题内容
     */
    private void setViewContent() {
        mycenterTopTitle.setLeftButtonContent(null, R.mipmap.pic_2_1_btn_back, null);
        mycenterTopTitle.setTitleButtonContent("个人中心", null, null);
        mycenterTopTitle.setRightButtonContent(null, R.mipmap.pic_2_2_btn_setting, null);
    }

    /**
     * 监听事件
     */
    private void setViewClickListener() {
        tvLogin.setOnClickListener(this);
        tvRegist.setOnClickListener(this);
        tvLogin.setOnClickListener(this);

        rlPersonalCenter.setOnClickListener(this);
        civUserImg.setOnClickListener(this);
        mycenterTopTitle.setOnLeftButtonClickListener(new TopTitleView.OnLeftButtonClickListener() {
            @Override
            public void onLeftBtnClick(View button) {
                String sessionkey = mCache.getAsString("sessionKeyAuth");
                if (sessionkey != null) {
                    StringTools.updatashopping = 1234;
                    mCache.put("sessionKeyLogin", sessionkey, ACache.TIME_HOUR);
                }
                MainActivity.flg = 200;
                finish();
                overridePendingTransition(R.anim.in_from_right_back_center, R.anim.out_to_left_back_center);
               /* finish();
                PersonalActivity.this.overridePendingTransition(R.anim.left_in, R.anim.left_out);*/
            }
        });
        mycenterTopTitle.setOnRightButtonClickListener(new TopTitleView.OnRightButtonClickListener() {
            @Override
            public void onRightBtnClick(View button) {
                Intent intent = new Intent(PersonalActivity.this, SettingActivity.class);
                startActivity(intent);
                PersonalActivity.this.overridePendingTransition(R.anim.left_in, R.anim.left_out);

            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        updateLoginLayout();
        if (CacheUtils.getBoolean(this, "Logined", false)) {
          /*  if (!headPath.exists()) {
                System.out.println("###$$headPath.exists()::" + headPath.exists());
                return;
            }*/
            getCustomerInfoBeanFromInternet();
            tvUserName.setText(sharedPress.getString("fullname"));
            if (StringTools.isLoaded)
                civUserImg.setImageBitmap(BitmapFactory.decodeFile(headPath.getAbsolutePath()));
            else
                civUserImg.setImageResource(R.drawable.avatar);
            int sex = sharedPress.getInt("gender");
            switch (sex) {
                // 0:是未知, 1:是男, 2:是女
                case 1:
                    ivGender.setVisibility(View.VISIBLE);
                    ivGender.setImageResource(R.mipmap.pic_2_3_icon_male);
                    break;
                case 2:
                    ivGender.setVisibility(View.VISIBLE);
                    ivGender.setImageResource(R.mipmap.pic_2_3_icon_female);
                    break;
                default:
                    ivGender.setVisibility(View.GONE);
                    break;
            }
        }
        // 获取微信登录成功的个人信息
        getInfoForLoginWeiXin();
    }

    private boolean updateLoginLayout() {
        //登陆过就显示顾客的信息
        boolean bIsLogout = CacheUtils.getBoolean(PersonalActivity.this, "Logined", false);//当第一次登陆时
        if (!bIsLogout) {
            // log out
            setViewContentUnLogin();//设置未登录的界面
        } else {
            setViewContentLogin();//设置登录的界面
        }
        return bIsLogout;
    }

    private void getCustomerInfoBeanFromInternet() {//网络获取数据
        LogUtils.d("开始请求用户信息:" + ACache.get(PersonalActivity.this).getAsString("sessionKeyLogin"));
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 取sessionKey
                    executeRequest(RequestUtils.getMLZRequestUserInfo(mContext, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String s) {
                            userBean = RequestUtils.userInfOnResponse(s);
                            MyApplication.getmInstance().setLoginUser(userBean);
                            Gson gson = new Gson();
                            UserInfo userInfo = gson.fromJson(s, UserInfo.class);

                            if (null != userInfo.getData()) {
                                // 用户名
                                final String fullName = userBean.getUserName();
                                sharedPress.putString("fullname", fullName);
//                        fullname = fullName;
                                // 头像URL
                                final String portrait = userBean.getHeadersImage();
                                //性别
                             /*
                                Double sex = (Double) userInfo.getData().getGender();
                                String sexx = String.valueOf(sex);
                                String sexxx = sexx.substring(0, sexx.indexOf("."));
                                final int gender = Integer.parseInt(sexxx);*/
                                final int gender = userInfo.getData().getGender();
                                sharedPress.putInt("gender", userInfo.getData().getGender());
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        //更新UI
                                        updateCustomInfoLayout(fullName, portrait, gender);
                                    }
                                });
                            }

                        }
                    }));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void updateCustomInfoLayout(final String fullname, final String portrait, final int gender) {

        tvUserName.setText(fullname);//显示用户名
//        if(!headPath.exists()||headPath.length()<100) {
        System.out.println("!!!!@@@@@@@@@");
//        imageLoader.displayImage(portrait, civUserImg, options);//显示头像
        ImageLoader.getInstance().displayImage(portrait, civUserImg);
        Bitmap bitmap = ImageLoader.getInstance().loadImageSync(portrait);
        try {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, new FileOutputStream(headPath));
            System.out.println("!!!!已经保存图片");
        } catch (Exception e) {
            System.out.println("!!!!保存图片出错" + e.toString());
        }
        switch (gender) {
            // 0:是未知, 1:是男, 2:是女
            case 1:
                ivGender.setVisibility(View.VISIBLE);
                ivGender.setImageResource(R.mipmap.pic_2_3_icon_male);
                break;
            case 2:
                ivGender.setVisibility(View.VISIBLE);
                ivGender.setImageResource(R.mipmap.pic_2_3_icon_female);
                break;
            default:
                ivGender.setVisibility(View.GONE);
                break;
        }
    }

    /**
     * 设置未登录的效果
     */
    private void setViewContentUnLogin() {
        llPersonalCenter.setVisibility(View.VISIBLE);
        tvLogin.setVisibility(View.VISIBLE);
        tvRegist.setVisibility(View.VISIBLE);

        rlPersonalCenter.setVisibility(View.GONE);
        civUserImg.setVisibility(View.GONE);
        tvUserName.setVisibility(View.GONE);
        ivGender.setVisibility(View.GONE);
        loginPullRight.setVisibility(View.GONE);
    }

    /**
     * 设置登录的效果
     */
    public void setViewContentLogin() {
        llPersonalCenter.setVisibility(View.GONE);
        tvLogin.setVisibility(View.GONE);
        tvRegist.setVisibility(View.GONE);
        rlPersonalCenter.setVisibility(View.VISIBLE);
        civUserImg.setVisibility(View.VISIBLE);
        tvUserName.setVisibility(View.VISIBLE);
        ivGender.setVisibility(View.VISIBLE);
        loginPullRight.setVisibility(View.VISIBLE);
    }

    private void initData() {
        list.add(new PersonalModel(R.mipmap.pic_2_4_icon_my_activity, "我的活动"));
        list.add(new PersonalModel(R.mipmap.pic_2_5_icon_my_point, "我的积分"));
        list.add(new PersonalModel(R.mipmap.pic_2_6_icon_my_wishlist, "我的收藏"));
        list.add(new PersonalModel(R.mipmap.pic_2_7_icon_my_order, "我的订单"));
        list.add(new PersonalModel(R.mipmap.pic_2_8_icon_real_name, "实名认证"));
        list.add(new PersonalModel(R.mipmap.pic_2_9_icon_address, "收货地址"));
        initList();
    }

    private void initList() {
        adapter = new PersonalAdapter(PersonalActivity.this, list, R.layout.personal_item_layout);
        personal.setAdapter(adapter);
        initListener();
    }

    private void initListener() {
        personal.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent it = new Intent();

                boolean isLogin = CacheUtils.getBoolean(PersonalActivity.this, "Logined", false);
                if (!isLogin) {
                    it.setClass(PersonalActivity.this, LoginActivity.class);
                } else {
                    switch (position) {
                        case 0:
                            it.setClass(PersonalActivity.this, MyNewActivity.class);
                            break;
                        case 1:
                            it.setClass(PersonalActivity.this, IntegralActivity.class);
                            break;
                        case 2:
                            it.setClass(PersonalActivity.this, CollectActivity.class);
                            break;
                        case 3:
                            it.setClass(PersonalActivity.this, MyOrder.class);
                            break;
                        case 4:
                            it.setClass(PersonalActivity.this, RealNameApprove.class);
                            it.putExtra(ConfigInfo.ACT_STATUS, "1000");
                            break;
                        case 5:
                            it.setClass(PersonalActivity.this, ReceiveAddress.class);
                            it.putExtra(ConfigInfo.ACT_STATUS, "1000");
                            break;
                        default:
                            break;

                    }
                }
                startActivity(it);
                PersonalActivity.this.overridePendingTransition(R.anim.left_in, R.anim.left_out);
            }
        });

    }


    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.tv_login://点击个人中心登录按钮监听
                intent = new Intent(PersonalActivity.this, LoginActivity.class);
                startActivity(intent);
                PersonalActivity.this.overridePendingTransition(R.anim.left_in, R.anim.left_out);
                break;
            case R.id.tv_regist://点击个人中心注册按钮监听
                intent = new Intent(PersonalActivity.this, RegistActivity.class);
                startActivity(intent);
                PersonalActivity.this.overridePendingTransition(R.anim.left_in, R.anim.left_out);
                break;
            case R.id.rl_personal_center://点击个人中心头像监听
                intent = new Intent(PersonalActivity.this, MyInfoActivity.class);
                startActivity(intent);
                PersonalActivity.this.overridePendingTransition(R.anim.left_in, R.anim.left_out);
                break;
            case R.id.top_right://点击头部右侧设置按钮
                intent = new Intent(PersonalActivity.this, SettingActivity.class);
                startActivity(intent);
                PersonalActivity.this.overridePendingTransition(R.anim.left_in, R.anim.left_out);
                break;

            case R.id.user_img://点击用户头像,弹出底部拍照窗口
                PhotoDialog.photo(PersonalActivity.this);
                PhotoDialog.btn_take_photo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        openCamera();//打开相机
                        PhotoDialog.pWindow.dismiss();
                    }
                });
                PhotoDialog.btn_pick_photo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 激活系统图库，选择一张图片
                        openPhoto();//打开相册
                        PhotoDialog.pWindow.dismiss();
                    }
                });
                PhotoDialog.btn_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PhotoDialog.pWindow.dismiss();
                    }
                });
                break;
            default:
//                showToast("程序");
                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        PersonalActivity.this.overridePendingTransition(R.anim.left_in, R.anim.left_out);
    }

    /*************************************
     * 以下代码为头像处理的哦
     ********************************************************************************/

    private static final int PHOTO_REQUEST_CAREMA = 1;
    private static final int PHOTO_REQUEST_GALLERY = 2;
    private static final int PHOTO_REQUEST_CUT = 3;
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private File tempFile;

    /**
     * 打开系统相册
     */
    private void openPhoto() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, PHOTO_REQUEST_GALLERY);

    }

    /**
     * 调用相机拍照
     */
    private void openCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
            Uri uri = Uri.fromFile(tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
        } else {
            Toast.makeText(PersonalActivity.this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 剪切图片
     *
     * @param uri
     * @function:
     * @author:Jerry
     * @date:2013-12-30
     */
    private void crop(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PHOTO_REQUEST_GALLERY) {
            if (data != null) {
                Uri uri = data.getData();
                Log.e("图片路径？？", data.getData() + "");
                crop(uri);
            }

        } else if (requestCode == PHOTO_REQUEST_CAREMA) {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                crop(Uri.fromFile(tempFile));
            } else {
                Toast.makeText(PersonalActivity.this, "未找到存储卡，无法存储照片！",
                        Toast.LENGTH_SHORT).show();
            }

        } else if (requestCode == PHOTO_REQUEST_CUT) {
            if (data != null) {
                final Bitmap bitmap = data.getParcelableExtra("data");
                //  iv.setImageBitmap(bitmap);
                //  civUserImg.setImageBitmap(bitmap);
                // 保存图片到internal storage
                upload(Bitmap2StrByBase64(bitmap), System.currentTimeMillis() + ".bmp");//头像将BASE64字符串发送到服务器
                FileOutputStream outputStream;
                try {
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                    out.flush();
                    // out.close();
                    // final byte[] buffer = out.toByteArray();
                    // outputStream.write(buffer);
                    outputStream = PersonalActivity.this.openFileOutput("_head_icon.jpg",
                            Context.MODE_PRIVATE);
                    out.writeTo(outputStream);
                    out.close();
                    outputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            try {
                if (tempFile != null && tempFile.exists())
                    tempFile.delete();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


    private void upload(String BaseString, String fileName) {
        LogUtils.d("qwe:" + BaseString);
        executeRequest(RequestUtils.PostHeadData(PersonalActivity.this, BaseString, fileName, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                getCustomerInfoBeanFromInternet();
            }
        }));
    }

    // 64base 转换器
    public String Bitmap2StrByBase64(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.JPEG, 70, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        LogUtils.d(Base64.encodeToString(bytes, Base64.DEFAULT).toString());
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

}
